<template>
    <div class="content">
        <div class="pic">
            <van-image width="10rem" fit="contain" :src="user" alt="" />
        </div>

        <main class="main">
            <p class="title" v-if="reswenjuanDetails?.title">{{ reswenjuanDetails?.title }}</p>
            <article class="article">
                <p>尊敬的先生/女士:</p>
                <div class="book" v-if="reswenjuanDetails?.description">
                    {{ reswenjuanDetails?.description }}
                </div>
            </article>
            <div class="obj" v-if="reswenjuanDetails?.hcemTemplatTopic.length">
                <p class="answer_title">本次共 {{ reswenjuanDetails?.hcemTemplatTopic.length }}题，请填写。</p>
            </div>

            <div class="test" v-for="v, k in text" :key="v.id">
                <div class="single">
                    <div v-if="v.topicType == 1">
                        <div class="single_title"> <span class="require" v-if="v.isRequired == 1">*</span>{{ v.topicName }}
                        </div>
                        <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                        <div style="padding-left: 30px;">
                            <van-radio-group v-model="value.myScore" v-for="value, key in v.scoreInfo">
                                <van-radio :name="value.name" style="margin-bottom: 10px;"
                                    @click="singleSelect(key, k, value.name)">{{ value.name }}</van-radio>
                            </van-radio-group>
                        </div>
                        <van-divider :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '20px auto', }">
                        </van-divider>
                    </div>
                </div>

                <div class="mutl">
                    <div v-if="v.topicType == 3">
                        <div class="mutl_title"> <span class="require" v-if="v.isRequired == 1">*</span>{{ v.topicName }}
                        </div>
                        <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                        <div style="padding-left: 30px;">
                            <van-checkbox-group v-model="value.myScore" v-for="value, key in v.scoreInfo">
                                <van-checkbox :name="value.name" shape="square" style="margin-bottom: 10px;"
                                    @click="mutleSelect(key, k)">{{ value.name
                                    }}</van-checkbox>
                            </van-checkbox-group>
                        </div>
                        <van-divider :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '20px auto', }">
                        </van-divider>
                    </div>
                </div>

                <div class="single_text">
                    <div v-if="v.topicType == 2">
                        <div class="single_text_title"> <span class="require" v-if="v.isRequired == 1">*</span>{{
                            v.topicName }}</div>
                        <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                        <van-cell-group inset>
                            <van-field class="single_border" v-model="v.scoreInfo" placeholder="请输入内容" />
                        </van-cell-group>
                        <van-divider :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '-2px auto', }">
                        </van-divider>
                    </div>
                </div>

                <div class="mutl_text">
                    <div v-if="v.topicType == 4">
                        <div class="leave">
                            <p class="leave_title"> <span class="require" v-if="v.isRequired == 1">*</span>{{ v.topicName }}
                            </p>
                            <div class="secondTitle" v-if="v.tip">({{ v.tip }})</div>
                            <div class="leave_message">
                                <van-cell-group inset>
                                    <van-field class="mutl_border" v-model="v.scoreInfo" rows="6" clearable autosize
                                        type="textarea" maxlength="500" placeholder="请输入内容" show-word-limit />
                                </van-cell-group>
                            </div>
                        </div>
                        <van-divider :style="{ color: '#D8D8D8', borderColor: '#999', width: '90%', margin: '30px auto', }">
                        </van-divider>
                    </div>
                </div>
            </div>
        </main>

        <div class="submit"><van-button type="primary" size="large" @click="throttle(submit)">提交</van-button></div>
    </div>
</template>

<script setup lang="ts">
import { showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { ref } from 'vue'
import { throttle } from '@/util/index'
import user from '@/assets/images/user.jpg'
import { userPost, wenjuanDetails,linkStatus,linkCount } from '@/api/index'
const route = useRoute()
const router = useRouter()
// const leaveMessage = ref('')
// const muti = ref('')
// const singeVlaue = ref('')
// const radio = ref('1');
// const checkbox = ref(['a']);

const reswenjuanDetails = ref()
const text = ref()
const wenjuanxiangqing = async (id ) => {
    let res = await wenjuanDetails(id)
    if (res.code == 500) {
      //  showToast('无法获取当前问卷，请刷新后重试')
        reswenjuanDetails.value = []
        router.push({ name: 'notice_fail' })
        return false
    }
    reswenjuanDetails.value = res.data
    text.value = res.data.hcemTemplatTopic
    text.value.map(v => {
        v.scoreInfo = JSON.parse(v.scoreInfo)
        if (v.topicType == 3) {
            v.scoreInfo.forEach((value) => {
                value['myScore'] = []
            })
        } else {
            v.scoreInfo.forEach((value) => {
                value['myScore'] = ''
            })
        }
        // console.log(v);
        return v
    });
    // reswenjuanDetails.value = res
    // return reswenjuanDetails
}
const init = async() => {
    let id = route.query.id
    let isEffective = route.query.linkId || ''
   // console.log(isEffective,'````');
    
    if(isEffective){
        const res = await linkStatus(isEffective)
        if(res.code !==200){  //链接失效直接跳走
            router.push({ name: 'notice_fail' })
        }else{  //计数
            const count = await linkCount(isEffective)
          //  console.log(count);
            
        }
       // console.log(res,121121);
    }else{
        showToast('无链接ID，请重新生成链接') 
       
    }
    wenjuanxiangqing(id)
}
init()
//单选结果赋值
const singleSelect = (key, k, params) => {
    text.value[k].scoreInfo.forEach((v) => {
        v.myScore = ''
        v.flag = false
    })
    text.value[k].scoreInfo[key].myScore = params
    text.value[k].scoreInfo[key].flag = true
}

let startTime: number = Date.now();
const formateSeconds = (endTime: number): string => {  //秒转分钟和小时
    let secondTime: number = parseInt(endTime)//将传入的秒的值转化为Number
    let min = 0// 初始化分
    let h = 0// 初始化小时
    let result = ''
    if (secondTime >= 60) {//如果秒数大于等于60，将秒数转换成整数
        min = parseInt(secondTime / 60)//获取分钟，除以60取整数，得到整数分钟
        secondTime = parseInt(secondTime % 60)//获取秒数，秒数取佘，得到整数秒数
        if (min >= 60) {//如果分钟大于等于60，将分钟转换成小时
            h = parseInt(min / 60)//获取小时，获取分钟除以60，得到整数小时
            min = parseInt(min % 60) //获取小时后取佘的分，获取分钟除以60取佘的分
        }
    }
    if (h) {
        result = `${h.toString().padStart(2, '0')}时:${min.toString().padStart(2, '0')}分:${secondTime.toString().padStart(2, '0')}秒`
    } else if (min) {
        result = `${min.toString().padStart(2, '0')}分:${secondTime.toString().padStart(2, '0')}秒`
    } else {
        result = `${secondTime.toString().padStart(2, '0')}秒`
    }
    return result
}

//多选结果赋值
const mutleSelect = (key, k) => {
    if (text.value[k].scoreInfo[key].flag) {
        text.value[k].scoreInfo[key].flag = false
    } else {
        text.value[k].scoreInfo[key].flag = true
    }
}
const userOptionList = ref<Array<any>>([])
const submit = async () => {
    text.value.map(v => {
        userOptionList.value.push({ topicId: v.id, score: v.scoreInfo, topicType: v.topicType })
    })
    let linkId = route.query.linkId || ''
    let source = route.query.source  || ''
    let doctorId = route.query.docId   //诊后医生ID
    //  let { operateDeptId } = data
    let operateDeptId = 1  //先写死
    let { hosp } = reswenjuanDetails.value
    let userPhone = { userPhone: '未填写' }
    let userName = { userName: '匿名' }
    let endTimeSecond: number = (Date.now() - startTime) / 1000
    let useTime = formateSeconds(endTimeSecond)   //使用时间
    let templateId = reswenjuanDetails.value.hcemTemplatTopic[0].templateId  //这里模板ID都一样，所以取第一个
    let params = { 'topicScoreInfo': JSON.stringify(userOptionList.value), operateDeptId, templateId, linkId, source, ...userName, ...userPhone, useTime, hosp }
    // console.log(params);
    // return 
    if(!isPass()) return 
    let resData = await userPost(params)
    if (resData.code == 200) {
        setTimeout(() => {
            router.push({ name: 'notice_success' })
        }, 2000)
    } else {
        showToast(resData.msg)
    }

}
const isPass = () => {
    let opt = text.value.map((v) => {
        //   console.log(v);
        const mytopicType = Number(v.topicType)
        if (v.isRequired == 1 && [1, 3].includes(mytopicType)) {
            let reslut = v.scoreInfo.findIndex(values => {
                return values.flag == true
            })
            if (reslut == -1) {
                showToast(`${v.topicName}，请选择一个选项`)
                return false
            } else {
                return true
            }
        } else if (v.isRequired == 1 && [2, 4].includes(mytopicType)) {
            if (v.scoreInfo == '') {
                showToast(`请填写${v.topicName}`)
                return false
            } else {
                return true
            }
        } else {
            return true
        }
    })
    if (opt.includes(false)) {
        return false
    } else {
        return true
    }
}

</script>

<style scoped lang="scss">
.content {
    padding-top: 48px;

    .pic {
        position: relative;
        z-index: 1;
    }

    .main {
        position: relative;
        z-index: 2;
        margin-top: -25px;
        background-color: #fff;
        // height: 100vh;
        border-radius: 30px;

        .title {
            padding: 18px 44px 15px 44px;
            margin: 0 auto;
            text-align: center;
            width: 287px;
            font-size: 22px;
            font-weight: 500;
            color: #3D3D3D;
            line-height: 32px;
        }

        .article {
            margin: 0 auto;
            width: 337px;
            // height: 102px;
            font-size: 14px;
            font-family: Source Han Sans CN-Regular, Source Han Sans CN;
            font-weight: 400;
            color: #999999;
            line-height: 17px;

            .book {
                margin-top: 20px;
                text-indent: 2em;
            }
        }

        .obj {

            .answer_title {
                margin: 30px 0 28px 20px;
                font-size: 14px;
                font-weight: 400;
                color: #999999;
                line-height: 20px;
            }
        }

        .require {
            color: red;
            padding-right: 5px;
            line-height: 15px;
        }

        .test {
            margin-left: 10px;

            .secondTitle {
                padding-left: 20px;
                padding-bottom: 10px;
                color: #999999;
            }

            .single {
                font-size: 14px;
                font-weight: 400;
                color: black;
                line-height: 17px;
                padding-top: 15px;

                .single_title {
                    padding-left: 20px;
                    padding-bottom: 10px;
                }
            }

            .mutl {
                font-size: 14px;
                font-weight: 400;
                color: black;
                line-height: 17px;

                .mutl_title {
                    padding-left: 20px;
                    padding-bottom: 10px;
                }
            }

            .single_text {
                font-size: 14px;
                font-weight: 400;
                color: black;
                line-height: 17px;

                .single_text_title {
                    padding-left: 20px;
                    // :deep .van-cell {
                    //     border: 1px solid #ccc !important;
                    // }
                }

                .single_border {
                    :deep .van-cell {
                        border: none;
                    }
                }


            }

            .mutl_text {
                .leave {

                    .leave_title {
                        font-size: 14px;
                        font-weight: 400;
                        color: black;
                        line-height: 17px;
                        padding-left: 20px;
                    }

                    .leave_message {
                        margin-right: 25px;
                        padding-bottom: 20px;

                        .mutl_border {
                            border: 1px solid #ccc !important;
                        }
                    }
                }
            }
        }
    }



    .submit {
        margin: 0 auto;
        width: 85%;
        padding: 20px 0;
    }
}
</style>